//
//  SEGDigitalComRootViewController.m
//  ExcellentHome
//
//  Created by Chiang on 16/8/9.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "SEGSubmitUserAtuhViewController.h"
#import "SEGDigitalComRootViewController.h"
#import "SEGAuthManagerViewManagerCell.h"
#import "SEGHouseAuthNotApplyView.h"
#import "SEGHouseUserListViewController.h"


#import "SEGNewAlertView.h"

@interface SEGDigitalComRootViewController ()<UITableViewDelegate,UITableViewDataSource ,SEGNewAlertViewDelegate>

@property(nonatomic,strong) UITableView *tableView;
/**
 未申请界面
 */
@property (nonatomic, strong)SEGHouseAuthNotApplyView *notApplyView;

@property(nonatomic, strong) SEGDigitalComRootViewModel *viewModel;
@end

@implementation SEGDigitalComRootViewController
#pragma mark - life cycle
- (instancetype)initWithViewModel:(SEGDigitalComRootViewModel*)viewModel{
    if (self == [super init]) {
        _viewModel = viewModel;
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self seg_requestAllMyHouseList];
}

-(void)loadView
{
    [super loadView];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), CGRectGetHeight(self.view.bounds) - kNavigationBarAndStatusBarHeight) style:UITableViewStyleGrouped];
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    self.tableView.backgroundColor=[UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;;
    [self.tableView registerClass:[SEGAuthManagerViewManagerCell class] forCellReuseIdentifier:kSEGAuthManagerViewManagerCellIdentifier];
    if(@available(iOS 11.0, *)){
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedSectionHeaderHeight  = self.tableView.estimatedSectionHeaderHeight > 0 ? self.tableView.estimatedSectionHeaderHeight : 0;
        self.tableView.estimatedSectionFooterHeight  = self.tableView.estimatedSectionFooterHeight > 0 ? self.tableView.estimatedSectionFooterHeight : 0;
    }
    [self.view addSubview:self.tableView];
}


- (void)seg_initFooterView
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 215)];
    footerView.backgroundColor = kColor_W;
    
    UILabel *label = [[UILabel alloc] init];
    label.font = kFont_13;
    label.textColor = kColor_3;
    label.text = @"如果您在本小区有多套房屋，需要分开认证";
    [footerView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footerView).offset(15);
        make.right.equalTo(footerView).offset(-15);
        make.top.equalTo(footerView).offset(80);
    }];
    label.textAlignment = NSTextAlignmentCenter;
    
    UIButton *authButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [authButton setTitle:@"申请住户认证" forState:UIControlStateNormal];
    [authButton setTitleColor:kColor_T forState:UIControlStateNormal];
    //    [authButton setBackgroundColor:kColor_T];
    authButton.titleLabel.font = kFont_16;
    authButton.layer.masksToBounds = YES;
    authButton.layer.cornerRadius = 14;
    authButton.layer.borderWidth = 0.5;
    authButton.layer.borderColor = kColor_T.CGColor;
    [footerView addSubview:authButton];
    [authButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(label.mas_bottom).offset(15);
        make.centerX.equalTo(footerView);
        make.width.mas_equalTo(120);
        make.height.mas_equalTo(28);
    }];
    [authButton addTarget:self action:@selector(seg_pushToSubmitUserAuthViewController) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableFooterView = footerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=self.title.length>0?self.title:@"房屋认证";
    
    self.view.backgroundColor = kColor_W;
    
    [self showCustomNavigationBackButton];
    [self segInitViews];
    [self bindViewModel];
}

#pragma mark - UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.viewModel.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

//自适应高度必须实现
- (CGFloat)tableView:(UITableView*)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return 82;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SEGAuthManagerViewManagerCell *cell = [tableView dequeueReusableCellWithIdentifier:kSEGAuthManagerViewManagerCellIdentifier forIndexPath:indexPath];
    if (self.viewModel.dataArray.count > indexPath.row) {
        SEGHouseInfoModel *model = self.viewModel.dataArray[indexPath.row];
        
        [cell setUpManagerCellWithModel:model];
        
        //审核中，判断该物业后台是否有录入“联系电话”，如未录入，不显示“致电管理处”按钮
        //审核失败，展示“重新申请“按钮
        if ([model.authFlag integerValue] == SEGHouseAuditStatus_Apply) {
            NSString *communityTel = ValueToString([SEGProfileManager sharedManager].profile.communityTel);
            if (communityTel.length <= 0) {
                cell.rightButton.hidden = YES;
            }else {
                cell.rightButton.hidden = NO;
            }
        } else if([model.authFlag integerValue] == SEGHouseAuditStatus_Refuse){
            cell.rightButton.hidden = NO;
        } else {
            cell.rightButton.hidden = YES;
        }
        
        cell.rightButton.tag = indexPath.row;
        if (cell.rightButton.allTargets.count == 0) {
            [cell.rightButton addTarget:self action:@selector(seg_rightButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        }
        cell.setDefaultButton.tag = indexPath.row;
        if (cell.setDefaultButton.allTargets.count == 0) {
            [cell.setDefaultButton addTarget:self action:@selector(seg_setDefaultButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SEGHouseInfoModel *model = self.viewModel.dataArray[indexPath.row];
    //审核通过 点击（热区：整栏）进入成员管理页面
    SEGHouseAuditStatus status = [model.authFlag integerValue];
    if (status == SEGHouseAuditStatus_Pass) {
        [self seg_pushHouserUserListViewControllerWithModel:model];
    }
}


#pragma mark - 按钮处理
- (void)seg_rightButtonPressed:(UIButton *)sender
{
    SEGHouseInfoModel *model = self.viewModel.dataArray[sender.tag];
    SEGHouseAuditStatus status = [model.authFlag integerValue];
    switch (status) {
        case SEGHouseAuditStatus_Apply:
        {
            //致电管理处
            [self seg_cellCommunityTel];
            break;
        }
        case SEGHouseAuditStatus_Pass:
        {
            //跳转至成员管理
            [self seg_pushHouserUserListViewControllerWithModel:model];
            break;
        }
        case SEGHouseAuditStatus_Refuse:
        {
            SEGSubmitUserAtuhViewModel *vm = [[SEGSubmitUserAtuhViewModel alloc] init];
            
            //在原基础上进行修改
            //楼栋
            SEGCommunityBuildListModel *buildModel = [[SEGCommunityBuildListModel alloc] init];
            buildModel.buildId = model.buildId;
            buildModel.name = model.buildName;
            //单元
            SEGUnitByBuildIdModel *unitModel = [[SEGUnitByBuildIdModel alloc] init];
            unitModel.unitId = model.unitId;
            unitModel.unit = model.unitName;
            //房号
            SEGHouseByUnitModel *houseModel = [[SEGHouseByUnitModel alloc] init];
            houseModel.houseId = model.houseId;
            houseModel.roomNo = model.roomNo;
            
            vm.buidingModel = buildModel;
            vm.unitModel = unitModel;
            vm.houseModel = houseModel;
            
            BOOL isSelfAuthApprove = [[[NSUserDefaults standardUserDefaults] objectForKey:@"SELFAPPROVE"] isEqualToString:@"1"];
            vm.isManual = !isSelfAuthApprove;
            
            //审核不通过 重新审核
            SEGSubmitUserAtuhViewController *submitVC = [[SEGSubmitUserAtuhViewController alloc] initWithViewModel:vm];
            [self.navigationController pushViewController:submitVC animated:YES];
            
            break;
        }
        default:
            break;
    }
}

- (void)seg_setDefaultButtonPressed:(UIButton *)sender
{
    //已经是默认房屋了 就不需要做操作
    if (sender.selected) {
        return;
    }
    
    [self.viewModel.defaultHouseCommand execute:@(sender.tag)];
    [SVProgressHUD show];
}

//致电管理处
- (void)seg_cellCommunityTel
{
    NSString *tel = [NSString stringWithFormat:@"tel:%@", ValueToString( [ SEGProfileManager sharedManager].profile.communityTel )];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tel]];
}

//跳转到用户审核界面
- (void)seg_pushToSubmitUserAuthViewController
{
    SEGSubmitUserAtuhViewModel *vm = [[SEGSubmitUserAtuhViewModel alloc] init];
    
    BOOL isSelfAuthApprove = [[[NSUserDefaults standardUserDefaults] objectForKey:@"SELFAPPROVE"] isEqualToString:@"1"];
    vm.isManual = !isSelfAuthApprove;
    
    SEGSubmitUserAtuhViewController *submitVC = [[SEGSubmitUserAtuhViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:submitVC animated:YES];
}

//跳转至成员管理
- (void)seg_pushHouserUserListViewControllerWithModel:(SEGHouseInfoModel *)model
{
    SEGHouseUserListViewModel *vm = [[SEGHouseUserListViewModel alloc] init];
    vm.houseId = model.houseId;
    vm.houseName = model.houseName;
    vm.userType = model.type;
    
    SEGHouseUserListViewController *userListVC = [[SEGHouseUserListViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:userListVC animated:YES];
}

#pragma mark - Init Views
-(void)segInitViews{}

#pragma mark - Layout
- (void)updateViewConstraints {
    [super updateViewConstraints];
}

#pragma mark - Private Methods

- (void)seg_requestAllMyHouseList {
    [self.viewModel.requestDataCommand execute:nil];
    [SVProgressHUD show];
}

#pragma mark - RAC Data Binding
- (void)bindViewModel {
    
    @weakify(self);
    //请求新用户房屋列表接口 包含用户认证的房屋，包含申请中、通过、未通过的房屋
    [[[self.viewModel.requestDataCommand executionSignals] switchToLatest] subscribeNext:^(NSNumber*  _Nullable x) {
        
        @strongify(self);
        
        [SVProgressHUD dismiss];
        
        if ([x boolValue]) {
            self.notApplyView.hidden = YES;
            self.viewModel.dataArray = self.viewModel.requestManager.houseInfoArray;
            [self.tableView reloadData];
            
            [self seg_initFooterView];
        }else{
            //失败、未申请
            self.notApplyView.hidden = NO;
        }
    }];
    
    [[[self.viewModel.defaultHouseCommand executionSignals] switchToLatest] subscribeNext:^(id  _Nullable x) {
        
        @strongify(self);
        
        [SVProgressHUD dismiss];
        //更新房屋列表
        [self seg_requestAllMyHouseList];
    }];
    
    [self.viewModel.messageSubject subscribeNext:^(NSString *  _Nullable x) {
        [SEGAlertView showTmepMessageWithMessage:x];
    }];
}

#pragma mark - getter
-(SEGDigitalComRootViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[SEGDigitalComRootViewModel alloc]init];
    }
    return _viewModel;
}

- (SEGHouseAuthNotApplyView *)notApplyView
{
    if (!_notApplyView) {
        _notApplyView = [[SEGHouseAuthNotApplyView alloc] initWithFrame:self.view.frame];
        _notApplyView.backgroundColor = kColor_W;
        [_notApplyView.authButton addTarget:self action:@selector(seg_pushToSubmitUserAuthViewController) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_notApplyView];
    }
    return _notApplyView;
}
#pragma mark setter
@end

